import router from './router/index'
import store from './store/index'
import NProgress from 'nprogress'
// import { Message } from 'element-ui'
import 'nprogress/nprogress.css'

import { getToken } from './utils/token'
const whiteList = ['/login', '/findPassword', '/testApp']

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const token = getToken()
  // console.log(store.getters.authorityList)
  if (token) {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      const hasRoleId = store.getters.roleId
      // const authorityList = store.getters.authorityList
      if (hasRoleId) {
        // console.log(to)
        // if (authorityList.length && authorityList.indexOf(to.meta.authority) === -1) {
        //   Message({
        //     type: 'error',
        //     message: '不允许访问',
        //     duration: 1000
        //   })
        //   next(from.path)
        // } else {
        //   if (!authorityList.length) {
        //     next('/login')
        //   }
        next({ replace: true })
        // }
      } else {
        await store.dispatch('user/getUserInfo')
        const addRoutes = await store.dispatch('permission/generateRoutes')
        router.addRoutes(addRoutes)
        next({ ...to, replace: true })
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done()
})

router.afterEach(() => {
  NProgress.done()
})
